package com.gd.deron.smartrobot.baobao.utils;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;

/**
 * 历史程序栈.
 * 
 * @author caiqingming
 * @time 2015/06/15
 */
public class ActivityUtil {

	/** The activity list. */
	private static List<Activity> activityList = null;

	/** The instance. */
	private static ActivityUtil instance = null;

	/**
	 * 返回该类的一个实例.
	 * 
	 * @return single instance of Historys
	 */
	private static ActivityUtil getInstance() {
		if (instance == null) {
			synchronized (ActivityUtil.class) {
				if (instance == null)
					instance = new ActivityUtil();
			}
		}
		return instance;
	}

	/**
	 * Instantiates a new historys.
	 */
	public ActivityUtil() {
		activityList = new ArrayList<Activity>();
	}

	/**
	 * 将一个程序Activity放入历史栈中.
	 * 
	 * @param activity the activity
	 */
	public static void putActivity(final Activity activity) {
		if (activityList == null)
			getInstance();
		SystemResource.getExecutorService().execute(new Runnable() {
			public void run() {
				activityList.add(activity);
				List<Activity> list = new ArrayList<Activity>();
				int size = activityList.size();
				for (int i = 0; i < size; i++) {
					Activity act = activityList.get(i);
					if (act != null && act.isFinishing()) {
						list.add(act);
					}
				}
				activityList.removeAll(list);
				list = null;
			}
		});
	}

	/**
	 * 结束所有在历史栈中的程序，并清空历史栈.
	 */
	public static void exitActivitys() {
		if (activityList == null)
			return;
		int size = activityList.size();
		for (int i = 0; i < size; i++) {
			Activity act = activityList.get(i);
			finish(act);
			act = null;
		}
		activityList.clear();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	/**
	 * Finish.
	 * 
	 * @param activity the activity
	 */
	private static void finish(Activity activity) {
		if (activity == null)
			return;
		try {
			activity.finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回收该类的数据资源.
	 */
	public static void recycle() {
		if (activityList != null) {
			activityList.clear();
			activityList = null;
		}
		instance = null;
	}
}
